﻿using SYJ.Model.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace SYJ.Logic
{
    public class AppContext
    {
        public const string USER_KEY = "UserKey";
        public const string HAS_PERMISSIONS_BY_USERID_KEY = "HasPermissionsByUserID";
        public static AppContext Current
        {
            get;
            set;
        }
        #region user

        public virtual void SetUser(SysUser user, List<SysPermission> permissions)
        {
            HttpContext.Current.Session[USER_KEY] = user;
            HttpContext.Current.Session[HAS_PERMISSIONS_BY_USERID_KEY] = permissions;
        }


        /// <summary>
        /// 获取当前用户的数据权限
        /// </summary>
        /// <returns></returns>
        public virtual int GetUserData_Scope(int permissions_id)
        {
            int data_scope = 1;
            List<SysPermission> permissions = HttpContext.Current.Session[HAS_PERMISSIONS_BY_USERID_KEY] as List<SysPermission>;
            permissions = permissions.Where(c => { return c.id == permissions_id; }).ToList();
            if (permissions != null && permissions.Count > 0 && permissions.First() != null)
                data_scope = permissions.First().id;
            else data_scope = 0;
            return data_scope;
        }
     

        /// <summary>
        /// 当前登录的用户信息
        /// 登录后保存信息到cookie
        /// </summary>
        public  SysUser User
        {
            get
            {
                if (HttpContext.Current != null)
                {
                    //HttpContext.Current.Session[USER_KEY] 主要由 CustomAuthorizeAttribute 处理。
                    var user = HttpContext.Current.Session[USER_KEY] as SysUser;

                    return user;
                }

                return null;
            }
        }
        /// <summary>
        /// 返回所有的权限定义
        /// </summary>
        /// <remarks>存放到session中，以免需要定时同步</remarks>
        public  List<SysPermission> Permissions
        {
            get
            {
                if (HttpContext.Current.Session[HAS_PERMISSIONS_BY_USERID_KEY] == null)
                {
                    HttpContext.Current.Session[HAS_PERMISSIONS_BY_USERID_KEY] = new List<SysPermission>();
                }
                return (List<SysPermission>)HttpContext.Current.Session[HAS_PERMISSIONS_BY_USERID_KEY];
            }
            protected set
            {
                HttpContext.Current.Session[HAS_PERMISSIONS_BY_USERID_KEY] = value;
            }
        }
        #endregion
    }
}
